<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-form-item label="滤波方法">
            <el-select v-model="form.filtering" placeholder="请选择滤波方法">
              <el-option
                v-for="dict in dict.type.filtering_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-form-item label="分析数据">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :http-request="uploadHttpRequest"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="uploadFiles"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只支持csv/mat格式文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">分析</el-button>
        <el-button @click="resetQuery">取消</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bearingData:signal:remove']"
        >删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="analysisData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="id" align="center">
      </el-table-column>
      <el-table-column prop="filteringName" label="滤波方法名称" align="center">
      </el-table-column>
      <el-table-column prop="createTime" label="时间" align="center">
      </el-table-column>
      <!--      <el-table-column prop="pic" label="分析结果" align="center">-->
      <!--        <template slot-scope="scope" align="left">-->
      <!--          <img :src="scope.row.pic"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="downloadPdf(scope.row)"
          >查看分析结果
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
  import {Analysis, delAnalysis, GetAnalysis, getPdf} from "../../../api/bearing/signal";

  export default {
    name: "Signal",
    dicts: ['filtering_type'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        Data: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 数据集表格数据
        datasetList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        fileList: [],
        analysisData: [],
        signalAnalysisType1: true,
        signalAnalysisType2: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          filtering: null,
          name: null,
          datasetName: null,
          conditionName: null,
          bearingName: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      }
    }
    ,
    /**
     * 数据发生改变
     */

    watch: {}
    ,

    /**
     * 创建完毕
     */

    created() {
      this.$nextTick(() => {
        this.getData();
      })
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 查询所有元器件信息
      getData() {
        GetAnalysis().then(response => {
          this.analysisData = response.rows;
          this.loading = false
        }).catch(() => {
          this.loading = false
        });
      },
      getList() {
        let formData = new FormData();
        if ("undefined" === typeof (this.form.files)) {
          this.$modal.msgError("请上传信号分析文件");
          return;
        }
        formData.append('files', this.form.files[0].raw);
        // 将其他数据写入json对象
        for (let key in this.form) {
          if (key !== "files") {
            formData.append(key, this.form[key])
          }
        }
        this.loading = true;
        Analysis(formData)
          .then(res => {
            if (res.msg === "success") {
              GetAnalysis().then(response => {
                this.analysisData = response.rows;
              });
            }
            // let s = 'data:image/jpg;base64,' + res.rows[0];
            // let p1 = s.replace(/[\r\n]/g, '');
            // let s1 = 'data:image/jpg;base64,' + res.rows[1];
            // let p2 = s1.replace(/[\r\n]/g, '');
            // let s2 = 'data:image/jpg;base64,' + res.rows[2];
            // let p3 = s2.replace(/[\r\n]/g, '');
            // if (this.form.filtering != null) {
            //   let s3 = 'data:image/jpg;base64,' + res.rows[3];
            //   let p4 = s3.replace(/[\r\n]/g, '');
            //   this.Data = [{type: "时域分析", pic: p1}, {type: "频域分析", pic: p2}, {type: "时频域分析", pic: p3},
            //     {type: "滤波分析", pic: p4}];
            // } else {
            //   this.Data = [{type: "时域分析", pic: p1}, {type: "频域分析", pic: p2}, {type: "时频域分析", pic: p3}];
            // }
            this.loading = false
          }).catch(() => {
          this.loading = false
        });
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      uploadHttpRequest(data) {
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      uploadFiles(item, fileList) {
        this.form.files = fileList
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.form.filtering = null;
        this.fileList = [];
        this.form.files = undefined;
        this.loading = true;
        this.Data = [];
        this.loading = false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除模型管理编号为"' + ids + '"的数据项？').then(function () {
          return delAnalysis(ids);
        }).then(() => {
          this.getData();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      changeAnalysisType1(type) {
        this.signalAnalysisType2 = !type
      },
      changeAnalysisType2(type) {
        this.signalAnalysisType1 = !type
      },
      downloadPdf(row) {
        let data = new FormData();
        data.append("id", row.id);
        data.append("filteringName", row.filteringName);
        getPdf(data).then(response => {
          // 创建一个新的Blob对象来表示响应数据
          const blob = new Blob([response], {type: 'application/pdf'});
          // 创建一个临时URL来表示这个Blob对象
          const url = URL.createObjectURL(blob);
          // 新增代码：在新窗口中预览PDF文件
          const previewWindow = window.open(url);
          // 新增代码：在新窗口中添加一个下载按钮
          previewWindow.onload = () => {
            const downloadButton = previewWindow.document.createElement("button");
            downloadButton.innerText = "Download";
            // 当用户点击下载按钮时，创建一个<a>元素并设置其href属性为临时URL
            downloadButton.onclick = () => {
              const link = document.createElement("a");
              link.href = url;
              // 设置download属性以便在用户点击链接时下载文件并将其保存为'signalAnalysisResult.pdf'
              link.download = 'signalAnalysisResult.pdf';
              // 将链接添加到文档中
              document.body.appendChild(link);
              // 模拟点击链接以下载PDF文件
              link.click();
            };
            // 将下载按钮添加到新窗口中
            previewWindow.document.body.appendChild(downloadButton);
          }
        })
      }
    }
  }
</script>

